package fragment.tabhostFragment;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.lanou.horo.myapplication.R;
import com.lanou.horo.myapplication.dbdao.PersonEntity;

import application.BasisApplication;
import dbdao.UserDBHepler;
import de.greenrobot.event.EventBus;
import fragment.AbsBaseFragment;
import utils.texttools.RegexValidateUtil;
import utils.roundimage.RoundedImageView;
import utils.texttools.StringUtil;

/**
 * Created by dllo on 15/12/2.
 */
public class PersonalMesage extends AbsBaseFragment implements View.OnClickListener {
    private TextView titleForAllTv, nameSizeTv;
    private ImageView titleForAllBack,changeUserBg;
    private EditText changeUserNn, changeUserSig;
    private CharSequence temp;//监听前的文本
    private int editStart;//光标开始位置
    private int editEnd;//光标结束位置
    private final int charMaxNum = 15;
    private UserDBHepler hepler;
    private Button saveUserChange;
    private TextView phoneNumber;
    private TextView email;
    private LinearLayout emaillayout;
    private RoundedImageView changeUserPh;
    private ContentResolver cr;


    @Override
    protected int getLayoutView() {
        return R.layout.fragment_personal_mesage;
    }

    @Override
    protected void initView() {
        titleForAllTv = findView(R.id.titleForAllTv);
        titleForAllBack = findView(R.id.titleForAllBack);
        nameSizeTv = findView(R.id.nameSizeTv);
        changeUserNn = findView(R.id.changeUserNn);
        changeUserSig = findView(R.id.changeUserSig);
        saveUserChange = findView(R.id.saveUserChange);
        phoneNumber = findView(R.id.phoneNumber);
        email = findView(R.id.email);
        emaillayout = findView(R.id.emaillayout);
        changeUserPh = findView(R.id.changeUserPh);
        cr = getActivity().getContentResolver();
        changeUserBg = findView(R.id.changeUserBg);
    }


    @Override
    protected void initData() {
        changeUserBg.setOnClickListener(this);
        changeUserPh.setOnClickListener(this);
        saveUserChange.setOnClickListener(this);
        hepler = UserDBHepler.getInstance();
        nameSizeTv.setText("最多可以输入15个字符");
        titleForAllTv.setText("个人资料");
        changeUserNn.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                temp = s;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                nameSizeTv.setText("还能输入" + (charMaxNum - s.length()) + "字符");
            }

            @Override
            public void afterTextChanged(Editable s) {
                editStart = changeUserNn.getSelectionStart();
                editEnd = changeUserNn.getSelectionEnd();
                if (temp.length() > charMaxNum) {
                    toastWarning("你输入的字数已经超过了限制！");
                    s.delete(editStart - 1, editEnd);
                    int tempSelection = editStart;
                    changeUserNn.setText(s);
                    changeUserNn.setSelection(tempSelection);
                }
            }
        });


        titleForAllBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goBack();
            }
        });

        phoneNumber.setText(BasisApplication.getUser().getPhoneNumber());
        emaillayout.setOnClickListener(this);
        if (!StringUtil.isEmpty(BasisApplication.getUser().getEmail())) {
            email.setText(BasisApplication.getUser().getEmail());
        } else {
            email.setText("输入邮箱");

        }
        if (!StringUtil.isEmpty(BasisApplication.getUser().getName())) {
            changeUserNn.setText(BasisApplication.getUser().getName());
        } else {
            changeUserNn.setText("");
        }
        if (!StringUtil.isEmpty(BasisApplication.getUser().getSignatye())) {
            changeUserSig.setText(BasisApplication.getUser().getSignatye());
        } else {
            changeUserSig.setText("签名");
        }
        if (BasisApplication.getUser().getUserImage() != null) {
            Bitmap bitmap = BytesToBimap(BasisApplication.getUser().getUserImage());
            changeUserPh.setImageBitmap(bitmap);
        } else {
            changeUserPh.setImageResource(R.mipmap.album_dialog_cat_cry);
        }
        if (BasisApplication.getUser().getUserBg()!=null){
            Bitmap bitmap = BytesToBimap(BasisApplication.getUser().getUserBg());
            changeUserBg.setImageBitmap(bitmap);
        }
        else {
            changeUserBg.setImageResource(R.mipmap.album_dialog_cat_cry);
        }

    }

    protected AlertDialog alertDialog;
    EditText emailEdt;

    Bitmap bitmapuser,bitmipbg;
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.changeUserBg:

                showPopu(changeUserBg);
                break;
            case R.id.changeUserPh:
                //访问本地相册
                getImage();
                break;
            case R.id.emaillayout:
                showlinDialog();
                break;
            case R.id.saveUserChange:
                PersonEntity entity =
                        hepler.getUsermsgByPhoneNumber(BasisApplication.getUser().getPhoneNumber());
                entity.setEmail(email.getText().toString());
                String name = changeUserNn.getText().toString();
                entity.setName(name);
                String sign = changeUserSig.getText().toString();
                entity.setSignatye(sign);


                changeUserPh.setDrawingCacheEnabled(true);
                if (changeUserPh.getDrawingCache() != null) {
                     bitmapuser = Bitmap.createBitmap(changeUserPh.getDrawingCache());
                }
                changeUserPh.setDrawingCacheEnabled(false);
                if (bitmapuser != null) {
                    entity.setUserImage(BitmapToBytes(bitmapuser));
                }

                changeUserBg.setDrawingCacheEnabled(true);//打开图片
                if (changeUserBg.getDrawingCache()!= null){
                    bitmipbg = Bitmap.createBitmap(changeUserBg.getDrawingCache());
                }
                changeUserBg.setDrawingCacheEnabled(false);
                if (bitmipbg != null){
                    entity.setUserBg(BitmapToBytes(bitmipbg));
                }
//                entity.setUserImage(bitmapToBytes);
//                entity.setUserBg(bytesBg);
                hepler.update(entity);
                BasisApplication.setUser(entity);
                EventBus.getDefault().post(entity);

                goBack();
                break;
        }
    }

    private void showPopu(View anchor) {
        PopupMenu pMenu = new PopupMenu(getContext(), anchor);
        pMenu.inflate(R.menu.menu_main);
        pMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.local) {//本地相册
                    getImageBg();
                }
                if (item.getItemId() == R.id.Other) {//网络解析

                }
                if (item.getItemId() == R.id.Camerasystem) {//系统相机

                }

                return false;
            }
        });
        pMenu.show();


    }
    //得到本地图片方法
    private void getImage() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//多媒体--图片--地址 跳转到图库地址
        startActivityForResult(intent, 200);

    }
    private void getImageBg(){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//多媒体--图片--地址 跳转到图库地址
        startActivityForResult(intent, 100);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //访问本地图片的方法
        if (requestCode==200){
            if (data != null) {
                Uri uri = data.getData();//图片中数据库的地址--图库地址
                Cursor cursor = cr.query(uri, null, null, null, null);
                if (cursor != null) {
                    //遍历cursor对象
                    while (cursor.moveToNext()) {
                        //获取文件路径地址
                        String imagePath = cursor.getString
                                (cursor.getColumnIndex(
                                        MediaStore.Images.Media.DATA));//取data字段 也就是图片对应的地址
                        //通过图片工厂去解析并显示
                        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                        Log.d("Personal", imagePath);
                        changeUserPh.setImageBitmap(bitmap);
//                        bitmapToBytes = BitmapToBytes(bitmap);
                    }

                    cursor.close();
                }
            }
        }

        if (requestCode==100){
            if (data != null) {
                Uri uri = data.getData();//图片中数据库的地址--图库地址
                Cursor cursor = cr.query(uri, null, null, null, null);
                if (cursor != null) {
                    //遍历cursor对象
                    while (cursor.moveToNext()) {
                        //获取文件路径地址
                        String imagePath = cursor.getString
                                (cursor.getColumnIndex(
                                        MediaStore.Images.Media.DATA));//取data字段 也就是图片对应的地址
                        //通过图片工厂去解析并显示
                        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                        Log.d("Personal", imagePath);
                        changeUserBg.setImageBitmap(bitmap);
//                                bytesBg= BitmapToBytes(bitmap);
                    }

                    cursor.close();
                }
            }
        }


    }

    private void showlinDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        final View view = LayoutInflater.from(getContext()).
                inflate(R.layout.emial_dialog, null);
        Button btn = (Button) view.findViewById(R.id.btnCustom);
        //点击确定按钮的监听
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                EditText emai = (EditText) view.findViewById(R.id.emailEt);
                String em = emai.getText().toString();
                if (RegexValidateUtil.checkEmail(em)) {
                    email.setText(em);
                } else {
                    toastWarning("您输入的邮箱不正确");
                }
                alertDialog.dismiss();
            }
        });
        builder.setView(view);
        alertDialog = builder.show();
    }
}
